package com.elinkway.infinitemovies.download;

import android.util.SparseArray;

import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;

import java.util.ArrayList;


/**
 * 控制下载任务 类
 *
 * 针对数据库和内存存储处理类
 */
public class DownloadProvider {
    public final static String TAG = "DownloadProvider";
    private SparseArray<DownloadFolderJob> folderJobs;
    private ArrayList<DownloadJob> mQueuedJobs; // 未完成仍在下载的
    private ArrayList<DownloadJob> mCompletedJobs; //已经下载完成

    private DownloadManager mDownloadManager;

    /**
     * 下载任务 数据库存储
     */
    private DownloadDao mDownloadDao;

    public DownloadProvider(DownloadManager mDownloadManager) {
        this.mDownloadManager = mDownloadManager;

        mQueuedJobs = new ArrayList<DownloadJob>();
        mCompletedJobs = new ArrayList<DownloadJob>();
        mDownloadDao = new DownloadDaoImpl();
        loadOldDownloads();
    }

    public ArrayList<DownloadJob> getAllDownloads() {
        ArrayList<DownloadJob> allDownloads = new ArrayList<DownloadJob>();
        allDownloads.addAll(mCompletedJobs);
        allDownloads.addAll(mQueuedJobs);
        return allDownloads;
    }

    public ArrayList<DownloadJob> getCompletedDownloads() {
        return mCompletedJobs;
    }

    public ArrayList<DownloadJob> getQueuedDownloads() {
        return mQueuedJobs;
    }

    public SparseArray<DownloadFolderJob> getFolderJobs() {
        return folderJobs;
    }

    public int getRemainNum() {
        if (null != folderJobs && folderJobs.size() > 0) {
            int size = folderJobs.size();
            int remainNum = 0;
            for (int i = 0; i < size; i++) {
                DownloadFolderJob downloadFolder = folderJobs.valueAt(i);
                SparseArray<DownloadJob> downloadJobs = downloadFolder
                        .getDownloadJobs();
                if (null != downloadJobs) {
                    remainNum = remainNum + downloadJobs.size();
                }
            }
            return remainNum;
        }
        return 0;
    }

    private void loadOldDownloads() {
        ArrayList<DownloadJob> oldDownloads = mDownloadDao.getAllDownloadJobs();
        if (null == folderJobs) {
            folderJobs = new SparseArray<DownloadFolderJob>();
        }
        for (DownloadJob dJob : oldDownloads) {
            if (dJob.getProgress() == 100) {
                mCompletedJobs.add(dJob);
                SparseArrayUtils.put(dJob, folderJobs);
                LogUtils.e("downLocal", "loadOldDownloads and folderJobs size is " + folderJobs.size());
            } else {
                if (dJob.getStatus() == DownloadJob.PAUSE) {
                    dJob.setDownloadManager(mDownloadManager);
                    mQueuedJobs.add(dJob);
                } else {
                    dJob.getEntity().setIndex(dJob.getIndex());
                    LogUtils.e("downLocal", "DownloadProvider setindex");
                    mDownloadManager.download(dJob.getEntity());
                }

            }
        }
        mDownloadManager.notifyObservers(); // 更新UI界面
    }

    public boolean queueDownload(DownloadJob downloadJob) {
        // 判断是否是第一次下载
        for (DownloadJob dJob : mCompletedJobs) {
            if (dJob.getEntity().getId()
                    .equals(downloadJob.getEntity().getId()))
                return false;
        }

        for (DownloadJob dJob : mQueuedJobs) {
            if (downloadJob.getEntity().getId()
                    .equals(dJob.getEntity().getId()))
                return false;
        }

        if (mDownloadDao.add(downloadJob.getEntity())) {
            mQueuedJobs.add(downloadJob);
            mDownloadManager.notifyObservers();
            return true;
        } else {
            return false;
        }
    }

    public void setStatus(DownloadEntity entity, int status) {
        mDownloadDao.setStatus(entity, status);
    }

    public void setIfWatch(DownloadEntity entity, String ifWatch) {
        mDownloadDao.setIfWatch(entity, ifWatch);
        LogUtils.e("downLocal", "全部的下载数量" + getAllDownloads().size());
        updateDownloads();
    }

    public boolean selectDownloadJobByMid(String mid) {
        return mDownloadDao.selectDownloadJobByMid(mid);
    }

    private void updateDownloads() {
        ArrayList<DownloadJob> oldDownloads = mDownloadDao.getAllDownloadJobs();
        if (null == folderJobs) {
            folderJobs = new SparseArray<DownloadFolderJob>();
        }
        LogUtils.e("downLocal", "已经缓冲的视频" + mCompletedJobs.size() + "");
        for (DownloadJob dJob : oldDownloads) {
            if (dJob.getProgress() == 100) {
                SparseArrayUtils.put(dJob, folderJobs);
                LogUtils.e("downLocal", "updateDownloads and folderJobs size is " + folderJobs.size());
            } else {

            }
        }
        mDownloadManager.notifyObservers(); // 更新UI界面
    }

    public boolean updateDownloadEntity(DownloadJob downloadJob) {
        return mDownloadDao.add(downloadJob.getEntity());
    }

    /**
     * 下载任务删除
     * @param job
     */
    public void removeDownload(DownloadJob job) {
        LogUtils.d(TAG, "----------remove job's progress is:" + job.getProgress() + "-------");
        if (job.getStatus() != DownloadJob.COMPLETE) {
            if (job.getStatus() == DownloadJob.DOWNLOADING)
                job.pauseOnOther(DownloadJob.PAUSE);
            LogUtils.d(TAG, "----------remove job at mQueuedJobs");
            mQueuedJobs.remove(job);
        } else {
            for (DownloadJob downloadJob : mCompletedJobs) {
                if (job.getEntity().getGlobaVid().equals(downloadJob.getEntity().getGlobaVid())) {
                    mCompletedJobs.remove(downloadJob);
                    LogUtils.d(TAG, "----------remove job at mCompletedJobs");
                    break;
                }
            }
        }
        mDownloadDao.remove(job);
    }

    /**
     * 下载成功：处理下载队列和下载完成队列还有数据库
     * @param job 下载任务
     */
    public void downloadCompleted(DownloadJob job) {
        LogUtils.i(CDNDownloadHandler.TAG, "下载成功：处理下载队列和下载完成队列还有数据库");
        MoviesConstant.isRefreshMyFragment = true;
        mQueuedJobs.remove(job);
        mCompletedJobs.add(job);
        SparseArrayUtils.put(job, folderJobs);
        LogUtils.e("downLocal", "downloadCompleted and folderJobs size is " + folderJobs.size());
        mDownloadDao.setStatus(job.getEntity(), DownloadJob.COMPLETE);
        mDownloadManager.notifyObservers();
        if (job.getCheck()) {//如果下载完成的job，是删除界面中被勾选的，那么回调，通知被勾选数量自减。
            mDownloadManager.notifyDownloadEnd(job);
        }
    }

    public ArrayList<DownloadJob> getDownloadJobsByMid(String mid) {
        return mDownloadDao.getDownloadJobsByMid(mid);
    }


}
